#include "ThemeSprite.h"
#include "log.h"
#include "SceneManager.h"
#include "GameData.h"
#include   <stdlib.h>

#define CLICK_TOUCH_DISTANCE 2

bool ThemeSprite::init() {
	CCSprite::init();

	setTouchEnabled(true);
}

void ThemeSprite::setCategory(int category){
	m_category = category;
}


void ThemeSprite::setId(int id){
	m_id = id;
}

void ThemeSprite::setTouchEnabled(bool enabled) {
	if (m_bTouchEnabled != enabled) {
		m_bTouchEnabled = enabled;

		if (enabled) {
			this->registerWithTouchDispatcher();
		} else {
			// have problems?
			CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(
					this);
		}

	}
}

void ThemeSprite::onExit(){
	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(
						this);
}

void ThemeSprite::registerWithTouchDispatcher() {
	CCDirector * director = CCDirector::sharedDirector();
	director->getTouchDispatcher()->addTargetedDelegate(this,-1, false);
}

bool ThemeSprite::isTouchInView(CCPoint point) {
	CCPoint p = getPosition();
	CCPoint anchorPoint = getAnchorPoint();
	CCSize size = getContentSize();
	CCRect rect = CCRectMake(p.x - size.width * anchorPoint.x,
		            p.y - size.height * anchorPoint.y,
		            size.width, size.height);
	bool result = rect.containsPoint(point);
	return result;
}

bool ThemeSprite::ccTouchBegan(CCTouch * pTouch, CCEvent *pEvent) {
	m_downPoint = pTouch->getLocation();
	m_downPoint = getParent()->convertToNodeSpace(m_downPoint);
	m_bDown = isTouchInView(m_downPoint);
	return true;
}

void ThemeSprite::ccTouchMoved(CCTouch * pTouch, CCEvent *pEvent) {

}

void ThemeSprite::ccTouchEnded(CCTouch * pTouch, CCEvent *pEvent) {
	CCPoint point = pTouch->getLocation();
	point = getParent()->convertToNodeSpace(point);
	int xDiff = abs(int(m_downPoint.x - point.x));
	int yDiff = abs(int(m_downPoint.y - point.y));

	bool isClicked = (xDiff < CLICK_TOUCH_DISTANCE)
			&& (yDiff) < CLICK_TOUCH_DISTANCE;
	bool result = isTouchInView(point);
	if (m_bDown && result && isClicked) { //down and up event should in the view
		startScene();
	}
}

void ThemeSprite::setName(const char * name) {
	memset(m_sName,0,sizeof(m_sName));
	memcpy(m_sName,name,strlen(name));
}

void ThemeSprite::setThumbPath(const char * path) {
	memset(m_thumbPath,0,sizeof(m_thumbPath));
	memcpy(m_thumbPath,path,strlen(path));
}

void ThemeSprite::startScene() {
	if (m_category == kThemeScene) {
		GameData::getInstance()->setCurrentThemeItemId(m_id);
		CCScene * scene = SceneManager::getScene(m_thumbPath);
		CCDirector::sharedDirector()->replaceScene(scene);
	}else{
		GameData::getInstance()->setCurrentThemeId(m_id);
		CCScene * scene = SceneManager::getScene(kThemeScene,m_id);
		CCDirector::sharedDirector()->replaceScene(scene);
	}

}
